﻿using System.IO;

namespace RegExpRegExpGenerator
{
    public class Loader
    {
        public Loader(string path)
        {
            this.path = path;
            RegExpGenerator.loadedFile = path; // Set current loaded file
        }

        public string path { get; set; }

        /// <summary>
        ///     Loads rules into RegExpRegExpGenerator
        /// </summary>
        public void Load()
        {
            // Default values
            string reg = "";
            string name = "";
            bool ignored = false;

            // Name, pattern, or namespace?
            int lineNumber = 0;

            // Current line
            string line = "";

            // Check for file
            if (!File.Exists(path))
            {
                return;
            }

            // Open stream
            var file = new StreamReader(path);

            // While the line exists
            while ((line = file.ReadLine()) != null)
            {
                if (string.IsNullOrWhiteSpace(line)) continue;

                if (lineNumber == 0)
                {
                    RegExpGenerator.ns = line;
                    lineNumber = 1;
                    continue;
                }

                if (lineNumber == 1) // We are getting the name
                {
                    lineNumber++;
                    name = line;
                }
                if (lineNumber == 2) // We are getting the pattern
                {
                    reg = line;
                    lineNumber = 3;
                }
                if (lineNumber == 3) // Checking if ignored
                {
                    ignored = bool.Parse(line);
                    var rule = new LexRule(name, reg, ignored);
                    RegExpGenerator.lexRules.Add(rule); // Add rule to LexRules
                    RegExpGenerator.rules.Add(rule.ToString()); // Add string to LexRules

                    // Reset default values
                    reg = "";
                    name = "";
                    ignored = false;
                    lineNumber = 1;
                }
            }

            // Close stream
            file.Close();
        }
    }
}